package com.noahsloan.nutils.streams;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Stream that gets it's exception from an external source.
 * 
 * @author noah
 * 
 */
public class CheckErrorOutputStream extends FilterOutputStream {

    /**
     * The exception to throw.
     */
    private volatile IOException e;

    public CheckErrorOutputStream(OutputStream out) {
        super(out);
    }

    @Override
    public void write(byte[] b) throws IOException {
        check();
        super.write(b);
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        check();
        super.write(b, off, len);
    }

    @Override
    public void write(int b) throws IOException {
        check();
        super.write(b);
    }

    @Override
    public void flush() throws IOException {
        check();
        super.flush();
    }

    @Override
    public void close() throws IOException {
        check();
        super.close();
    }

    public void setException(IOException e) {
        this.e = e;
    }

    private void check() throws IOException {
        if (e != null) {
            throw e;
        }
    }
}
